﻿using And.Shp.Common.ServiceLocation;
using Microsoft.SharePoint.Utilities;
using SharepointCommon;
using System;
using System.Collections.Generic;
using Uportal.Shp.Core.Model;

namespace Uportal.Shp.Core.Services
{
    public class AppPackage : IAppPackage
    {
        private readonly IDictionary<string, object> _listCache = new Dictionary<string, object>();

        protected AppPackage()
        {
        }

        // use parametrized constructor because consider using on different sites of one farm
        public AppPackage(string webUrl)
        {
            var logger = SL.GetCurrent().GetInstance<ILogger>();
            try
            {
                Web = WebFactory.Open(webUrl);

                Settings = Settings.Get();
            }
            catch (Exception ex)
            {
                logger.Exception(ex);
                throw new Exception("Error while construct ApplicationPackage", ex);
            }
        }

        public Settings Settings { get; protected set; }

        public IQueryWeb Web { get; protected set; }

        public IQueryList<FeedbackToManagmentItem> Feedback { get { return GetListByUrl<FeedbackToManagmentItem>(FeedbackToManagmentItem.ListUrl); } }

        public void Dispose()
        {
            if (Web != null)
                Web.Dispose();
        }

        private IQueryList<T> GetListByUrl<T>(string listWebRelativeUrl) where T : Item, new()
        {
            if (_listCache.ContainsKey(listWebRelativeUrl)) return (IQueryList<T>)_listCache[listWebRelativeUrl];
            var url = SPUrlUtility.CombineUrl(Web.Web.ServerRelativeUrl, listWebRelativeUrl);
            var list = Web.GetByUrl<T>(url);
            _listCache.Add(listWebRelativeUrl, list);
            return list;
        }

        private IQueryList<T> GetListById<T>(string listId) where T : Item, new()
        {
            if (_listCache.ContainsKey(listId)) return (IQueryList<T>)_listCache[listId];
            var list = Web.GetById<T>(new Guid(listId));
            _listCache.Add(listId, list);
            return list;
        }

    }
}
